// 存储检测到的资源URL
let resources = {
  images: new Set(),
  videos: new Set(),
  audios: new Set()
};

// 创建固定面板
function createPanel() {
  fetch(chrome.runtime.getURL('content_panel.html'))
    .then(response => response.text())
    .then(html => {
      const div = document.createElement('div');
      div.innerHTML = html;
      document.body.appendChild(div.querySelector('#resource-sniffer-panel'));
    });
}

// 检测页面中的资源
function detectResources() {
  // 检测图片
  document.querySelectorAll('img').forEach(img => {
    if (img.src && img.src.startsWith('http')) {
      resources.images.add({ url: img.src });
    }
  });

  // 检测视频
  document.querySelectorAll('video').forEach(video => {
    if (video.src && video.src.startsWith('http')) {
      resources.videos.add({ url: video.src });
    }
    // 检测video标签中的source标签
    video.querySelectorAll('source').forEach(source => {
      if (source.src && source.src.startsWith('http')) {
        resources.videos.add({ url: source.src });
      }
    });
  });

  // 检测音频
  document.querySelectorAll('audio').forEach(audio => {
    if (audio.src && audio.src.startsWith('http')) {
      resources.audios.add({ url: audio.src });
    }
    // 检测audio标签中的source标签
    audio.querySelectorAll('source').forEach(source => {
      if (source.src && source.src.startsWith('http')) {
        resources.audios.add({ url: source.src });
      }
    });
  });
}

// 初始检测
detectResources();

// 创建固定面板
createPanel();

// 创建MutationObserver监听DOM变化
const observer = new MutationObserver((mutations) => {
  let shouldDetect = false;
  
  mutations.forEach(mutation => {
    if (mutation.addedNodes.length > 0) {
      shouldDetect = true;
    }
  });

  if (shouldDetect) {
    detectResources();
  }
});

// 开始监听DOM变化
observer.observe(document.body, {
  childList: true,
  subtree: true
});

// 监听来自popup的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'getResources') {
    // 将Set转换为数组
    sendResponse({
      images: Array.from(resources.images),
      videos: Array.from(resources.videos),
      audios: Array.from(resources.audios)
    });
  }
  return true;
});